<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>初试Canvas</title>
    <style>
      canvas {
        position: fixed;
        left: 0;
        top: 0;
        background: #222;
      }
    </style>
  </head>
  <body>
    <canvas></canvas>
  </body>
  <script type="text/javascript">
    const canvas = document.querySelector('canvas')
    const ctx = canvas.getContext('2d')
    function init() {
      canvas.width = window.innerWidth
      canvas.height = window.innerHeight
    }
    init()
    // 开启路径
    // ctx.beginPath()
    // // 初始点
    // ctx.moveTo(100, 100)
    // // 目标点划线
    // ctx.lineTo(200, 150)
    // ctx.lineTo(200, 200)
    // // 闭合路径
    // ctx.closePath()
    // // 描边颜色
    // ctx.strokeStyle = '#ccc'
    // // 绘制
    // ctx.stroke()

    // ctx.beginPath()
    // // 绘制圆 参数：圆心点(x,y), 半径r,起始角度，结束角度，顺时针/逆时针
    // ctx.arc(300, 300, 50, 0, Math.PI * 2, false)
    // // 填充颜色
    // ctx.fillStyle = '#ccc'
    // // 填充
    // ctx.fill()

    class Point {
      constructor(x, y, r, color) {
        this.x = x
        this.y = y
        this.r = r
        this.color = color
      }
      draw() {
        ctx.beginPath()
        ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false)
        ctx.fillStyle = this.color
        ctx.fill()
      }
    }

    class Graph {
      constructor() {
        // 两点之间极限距离
        this.maxDis = 300
        this.point = new Array(10)
          .fill(0)
          .map(
            () =>
              new Point(
                Math.random() * canvas.width,
                Math.random() * canvas.height,
                5,
                '#ccc'
              )
          )
      }
      draw() {
        for (let i = 0; i < this.point.length; i++) {
          const p1 = this.point[i]
          p1.draw()
          for (let j = i + 1; j < this.point.length; j++) {
            const p2 = this.point[j]
            const d = Math.sqrt(
              Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2)
            )
            if (d > this.maxDis) {
              continue
            }

            ctx.beginPath()

            ctx.moveTo(p1.x, p1.y)

            ctx.lineTo(p2.x, p2.y)

            ctx.closePath()

            ctx.strokeStyle = `rgba(255,255,255,${1 - d / this.maxDis})`

            ctx.stroke()
          }
        }
      }
    }
    const g = new Graph()
    g.draw()
  </script>
</html>
